package com.mongdb.mongdb;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.convert.CustomConversions;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.scheduling.annotation.EnableAsync;

import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
@EnableAsync
public class MongdbApplication {
//	@Bean
//	public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory,
//													   MongoMappingContext context, BeanFactory beanFactory, MongoCustomConversions conversions) {
//		DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
//		MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
//		// 去除文档_class
//		mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
//		mappingConverter.setCustomConversions(conversions);
//		return mappingConverter;
//	}

	//以配置文件的形式将自定义的convernet加入MongoTemplate中


	@Autowired
	MongoDbFactory factory;
	@Bean
	public MongoCustomConversions customConversions() {

		List<Converter<?,?>> converters = new ArrayList<Converter<?,?>>();

		converters.add(new TimestampConverter());

		return new MongoCustomConversions(converters);
}
	@Bean
	public MongoTemplate mongoTemplate() throws Exception {

		MongoTemplate mongoTemplate = new MongoTemplate(factory);
		MappingMongoConverter mongoMapping = (MappingMongoConverter) mongoTemplate.getConverter();
		mongoMapping.setCustomConversions(customConversions()); // tell mongodb to use the custom converters
		mongoMapping.afterPropertiesSet();
		return mongoTemplate;

	}





	public static void main(String[] args) {
		SpringApplication.run(MongdbApplication.class, args);
	}

}
